//
//  AppDelegate.m
//  Kelindo
//
//  Created by Gianluca Puglia on 18/04/13.
//  Copyright (c) 2013 Gianluca Puglia. All rights reserved.
//

#import "AppDelegate.h"
#import "ResultData.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayOutputView:) name:@"finished" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeOutputView) name:@"close" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStatusBar:) name:@"updateStatusBar" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgressBar:) name:@"updateProgressBar" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finalizeFinished) name:@"finalizeFinished" object:nil];
    [_statusBar setStringValue:@"Ready.."];
}

- (void)updateProgressBar:(NSNotification *)notification {
    NSDictionary *dict = (NSDictionary *)[notification object];
    NSNumber *done = [dict objectForKey:@"done"];
    NSNumber *total = [dict objectForKey:@"total"];
    [_progressBar setDoubleValue:([done floatValue] / [total floatValue])*100];
}

- (IBAction)onlyConversionChange:(id)sender {
    if (_onlyConversion.state == NSOnState) {
        [_comboBoxFormat setEnabled:YES];
        [_comboBoxBitrate setEnabled:YES];
    }
    else {
        [_comboBoxFormat setEnabled:NO];
        [_comboBoxBitrate setEnabled:NO];
    }
}

- (void)updateStatusBar:(NSNotification *)notification {
    NSDictionary *dict = (NSDictionary *)[notification object];
    NSNumber *done = [dict objectForKey:@"done"];
    NSNumber *total = [dict objectForKey:@"total"];
    [_statusBar setStringValue:[NSString stringWithFormat:@"Complete %d/%d",[done intValue], [total intValue]]];
}

- (void)displayOutputView:(NSNotification *)notification {
    _outputPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, 950, 600)
                                    styleMask:NSTitledWindowMask | NSClosableWindowMask
                                      backing:NSBackingStoreBuffered
                                        defer:NO];

    [_outputPanel center];
    [_outputPanel setBecomesKeyOnlyIfNeeded:NO];
    [_outputPanel setFloatingPanel:YES];
    [_outputPanel makeKeyAndOrderFront:_window];
    
    _outputVC = [[OutputVC alloc] initWithNibName:@"OutputVC" bundle:nil];
    _outputVC.rd = (ResultData *)[notification object];
    [_outputPanel.contentView addSubview:_outputVC.view];
    _outputVC.view.frame = ((NSView*)_outputPanel.contentView).bounds;
}

- (void)finalizeFinished {
    [_statusBar setStringValue:@"Done."];
    [_progressBar setDoubleValue:100];
}

- (void)closeOutputView {
    [_statusBar setStringValue:@"Ready.."];
    [_progressBar setDoubleValue:0];
    [_outputPanel close];
}

@end
